<template>
  <view class="class-form-page">
    <view class="form-card">
      <uni-forms ref="form" :modelValue="formData" label-width="160rpx">
        <!-- 班级名称 -->
        <uni-forms-item label="班级名称" required name="className">
          <input
            type="text"
            v-model="formData.className"
            placeholder="请输入班级名称"
            class="form-input"
          />
        </uni-forms-item>

        <!-- 教师选择 -->
        <uni-forms-item label="选择教师" required name="teacherId">
          <uni-data-select
            v-model="formData.teacherId"
            :localdata="teacherList"
            placeholder="请选择教师"
            @change="handleTeacherChange"
            class="form-select"
            :clearable="false"
          ></uni-data-select>
        </uni-forms-item>

        <!-- 课程选择 -->
        <uni-forms-item label="选择课程" required name="subjectId">
          <uni-data-select
            v-model="formData.subjectId"
            :localdata="subjectList"
            placeholder="请选择课程"
            @change="handleSubjectChange"
            class="form-select"
            :clearable="false"
          ></uni-data-select>
        </uni-forms-item>

        <!-- 提交按钮 -->
        <view class="button-group">
          <button class="primary" @click="submitForm" :loading="isLoading">
            {{
              isLoading
                ? isEditMode
                  ? '更新中...'
                  : '添加中...'
                : isEditMode
                ? '更新班级'
                : '添加班级'
            }}
          </button>
        </view>
      </uni-forms>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getTeacherListAPI } from '@/pagesOrgan/services/teacher'
import { getCoursesAPI } from '@/pagesOrgan/services/course'
import {
  getClassRoomDetailAPI,
  addClassRoomAPI,
  updateClassRoomAPI,
} from '@/pagesOrgan/services/classRoom'
import type { ClassRoomItem } from '@/types/classRoom'

// 路由和导航
const isEditMode = ref(false)
const title = ref('添加班级')
const isLoading = ref(false)

// 表单数据
const formData = ref<ClassRoomItem>({})

// 选择器数据
const teacherList = ref<{ value: number; text: string }[]>([])
const subjectList = ref<{ value: number; text: string }[]>([])

// 获取教师列表
const getTeacherList = async () => {
  try {
    const res = await getTeacherListAPI({ pageNum: 1, pageSize: 100 })
    teacherList.value = res.data.rows
      .map((teacher: any) => ({
        value: teacher.id || 0,
        text: teacher.teacherName || '',
      }))
      .filter((item: any) => item.text) // 过滤无效数据
  } catch (error) {
    console.error('获取教师列表失败:', error)
    uni.showToast({ title: '获取教师失败', icon: 'none' })
  }
}

// 获取课程列表
const getCourseList = async () => {
  try {
    const res = await getCoursesAPI({ pageNum: 1, pageSize: 100 })
    subjectList.value = res.data.rows
      .map((course: any) => ({
        value: course.id || 0,
        text: course.subjects || course.subject || '',
      }))
      .filter((item: any) => item.text) // 过滤无效数据
  } catch (error) {
    console.error('获取课程列表失败:', error)
    uni.showToast({ title: '获取课程失败', icon: 'none' })
  }
}

// 获取班级详情（编辑模式）
const getClassDetail = async (id: number) => {
  isLoading.value = true
  try {
    const res = await getClassRoomDetailAPI(id)
    formData.value = res.data
    // 编辑模式下，设置已选教师和课程的值
    if (res.data.teacherId) {
      formData.value.teacherId = Number(res.data.teacherId)
    }
    if (res.data.subjectId) {
      formData.value.subjectId = Number(res.data.subjectId)
    }
  } catch (error) {
    console.error('获取班级详情失败:', error)
    uni.showToast({ title: '加载班级数据失败', icon: 'none' })
  } finally {
    isLoading.value = false
  }
}

// 提交表单
const submitForm = async () => {
  // 表单验证
  if (!formData.value.className) {
    uni.showToast({ title: '请输入班级名称', icon: 'none' })
    return
  }
  if (!formData.value.teacherId) {
    uni.showToast({ title: '请选择教师', icon: 'none' })
    return
  }
  if (!formData.value.subjectId) {
    uni.showToast({ title: '请选择课程', icon: 'none' })
    return
  }

  isLoading.value = true
  try {
    if (isEditMode.value) {
      await updateClassRoomAPI(formData.value)
    } else {
      await addClassRoomAPI(formData.value)
    }

    uni.showToast({
      title: isEditMode.value ? '班级更新成功' : '班级添加成功',
      icon: 'success',
    })

    // 通知列表页刷新数据
    uni.$emit('refreshClassList')
    uni.navigateBack()
  } catch (error) {
    console.error('提交班级数据失败:', error)
    uni.showToast({
      title: isEditMode.value ? '班级更新失败' : '班级添加失败',
      icon: 'none',
    })
  } finally {
    isLoading.value = false
  }
}

// 处理教师选择 - 修复事件处理
const handleTeacherChange = (e: any) => {
  // 检查参数结构，不同版本的组件可能返回不同格式的参数
  const selectedValue = e?.value !== undefined ? e.value : e
  const selectedTeacher = teacherList.value.find((item) => item.value === parseInt(selectedValue))
  if (selectedTeacher) {
    formData.value.teacherName = selectedTeacher.text
    // 确保v-model绑定的值也更新
    formData.value.teacherId = selectedTeacher.value
  }
}

// 处理课程选择 - 修复事件处理
const handleSubjectChange = (e: any) => {
  // 检查参数结构
  const selectedValue = e?.value !== undefined ? e.value : e
  const selectedSubject = subjectList.value.find((item) => item.value === parseInt(selectedValue))
  if (selectedSubject) {
    formData.value.subjectName = selectedSubject.text
    // 确保v-model绑定的值也更新
    formData.value.subjectId = selectedSubject.value
  }
}

// 页面加载时初始化数据
const initData = async (options?: any) => {
  // 先加载教师和课程列表
  await Promise.all([getTeacherList(), getCourseList()])

  // 再处理编辑模式
  if (options?.id) {
    isEditMode.value = true
    title.value = '编辑班级'
    await getClassDetail(parseInt(options.id))
  } else {
    title.value = '添加班级'
  }
}

// 页面加载时初始化数据
onLoad(async (options) => {
  await initData(options)
})

// 监听全局刷新事件
onMounted(() => {
  uni.$on('refreshClassList', () => {
    if (isEditMode.value && formData.value.id) {
      getClassDetail(formData.value.id)
    }
  })
})
</script>

<style scoped lang="scss">
.class-form-page {
  padding: 0;
  background-color: #f5f5f5;
  min-height: 100vh;
  box-sizing: border-box;
}

/* 自定义导航栏样式 */
.custom-nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 90rpx;
  padding: 0 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #e0e0e0;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
}

.nav-back {
  display: flex;
  align-items: center;
}

.back-icon {
  font-size: 36rpx;
  color: #333;
  margin-right: 8rpx;
}

.back-text {
  font-size: 28rpx;
  color: #333;
}

.nav-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.nav-right {
  width: 60rpx;
}

/* 表单卡片样式 - 参考HomeworkFormCard */
.form-card {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 32rpx;
  margin: 120rpx 20rpx 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

/* 表单项目样式 */
.uni-forms-item {
  margin-bottom: 32rpx !important;
}

.uni-forms-item__label {
  font-size: 28rpx !important;
  color: #333 !important;
  width: 160rpx !important;
}

/* 输入框样式优化 - 参考HomeworkFormCard */
.form-input,
.form-select {
  width: 100% !important;
  height: 88rpx !important;
  border: 1rpx solid #e5e9f2 !important;
  border-radius: 8rpx !important;
  padding: 0 20rpx !important;
  box-sizing: border-box !important;
  background-color: #fff !important;
  font-size: 28rpx !important;
}

/* 按钮样式优化 - 参考HomeworkFormCard */
.button-group {
  margin-top: 40rpx;
  padding: 0 20rpx;
}

.button-group button {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  background-color: #409eff;
  color: #fff;
  font-size: 32rpx;
  border-radius: 45rpx;
  border: none;
  transition: all 0.3s ease;
}

.button-group button:active {
  background-color: #3a8ee6;
  transform: scale(0.98);
}

/* 按钮加载状态样式 */
.button-group button[loading] {
  opacity: 0.8;
}
</style>
